<?php

namespace common\models\course;

use Yii;
use yii\base\Exception;

/**
 * This is the model class for table "{{%course_group}}".
 *
 * @property int $id
 * @property string $name 群名称
 * @property string $logo 群头像
 * @property string $rongyun_id 融云群组ID
 * @property int $nums 群组人数
 * @property int $user_id 创建人用户ID
 * @property int $course_id 课程ID
 * @property int $listorder 显示排序
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class CourseGroup extends \common\base\ActiveRecord {

    use \common\traits\Constants;
    use \common\traits\TimestampBehavior;
    use \common\traits\QueryInstanceActiveRecord;

    const STATUS_ACTIVE = 10;
    const STATUS_DEFAULT = 0;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%course_group}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['name'], 'required'],
            [['nums', 'user_id', 'course_id', 'rongyun_id', 'listorder', 'status', 'created_at', 'updated_at'], 'integer'],
            [['name'], 'string', 'max' => 100],
            [['logo'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => '群名称',
            'logo' => '群头像',
            'rongyun_id' => '融云群组ID',
            'nums' => '群组人数',
            'user_id' => '创建人用户ID',
            'course_id' => '课程ID',
            'listorder' => '显示排序',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    /**
     * @param integer $courseid 课程ID
     */
    public static function findByCourse($courseid) {
        return static::findOne(['course_id' => $courseid]);
    }

    /**
     * @param \common\models\course\Course $course 课程模型
     */
    public static function build($course) {
        $userids = [];

        $model = static::findOrNew([
            'course_id' => $course->id,
        ]);
        $model->attributes = [
            'name' => $course->name,
            'logo' => $course->cover,
        ];

        if ($course->teacher && $course->teacher->user_id) {
            $userids[] = $course->teacher->user_id;
        }
        if ($course->school && $course->school->president_id) {
            $president = \common\models\teacher\Teacher::findOne($course->school->president_id);
            if ($president && $president->user_id) {
                $userids[] = $president->user_id;
            }
        }

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception(print_r($model->getErrors(), true));
            }
            //多分类写入保存
            if (!empty($userids)) {
                foreach ($userids as $user_id) {
                    $guser = CourseGroupUsers::findOrNew([
                        'user_id' => $user_id,
                        'group_id' => $model->id,
                    ]);
                    if (!$guser->save()) {
                        throw new Exception(print_r($guser->getErrors(), true));
                    }
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            // 记录回滚（事务回滚）
            $transaction->rollBack();
            Yii::error($e->getMessage());
            return false;
        }

        if (!$model->rongyun_id) {
            $group = Yii::$app->rongyun->transport('group');
            Yii::error($userids);
            $created = $group->create($userids, $model->id, $model->name);
            if ($created !== false) {
                $model->rongyun_id = $model->id;
            }
        }

        return $model->save();
    }

    /**
     * @param integer $courseid 课程ID
     */
    public static function close($courseid) {
        $model = static::findByCourse($courseid);
        $model->status = static::STATUS_ACTIVE;
        return $model->save();
    }

    /**
     * @param integer $courseid 课程ID
     */
    public static function joinByCourse($userid, $courseid) {
        $model = static::findByCourse($courseid);
        return static::joinGroup($userid, $model);
    }

    /**
     * @param integer $courseid 课程ID
     */
    public static function joinGroup($userid, $group = null) {
        if (!$group) {
            return false;
        }
        $join = CourseGroupUsers::findOrNew([
            'user_id' => $userid,
            'group_id' => $group->id,
        ]);
        if (!$join->save()) {
            return false;
        }
        $transport = Yii::$app->rongyun->transport('group');
        $created = $transport->join([$userid], $group->id, $group->name);
        if ($created !== false) {
            $options = [
                'toUserId' => $userid,
            ];
            $msg = '欢迎您参加本课程，我是本课程的主讲老师，有什么问题可以随时在这里和我沟通';
            $message = Yii::$app->rongyun->transport('message');
            $res = $message->publishGroup($group->user_id, $group->id, $msg, [], $options);
            Yii::error([
                'response' => $res
            ], __METHOD__);
            $group->nums = $group->nums + 1;
            return $group->save();
        }
        return false;
    }

}
